package com.director.hibernate.json.impl.gson;

import com.director.core.json.impl.gson.GsonBuilderConfigurer;
import com.google.gson.GsonBuilder;
import org.hibernate.EntityMode;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;

import java.util.Map;

/**
 * @author Simone Ricciardi
 * @version 1.0, 10/15/2011
 */
public class HibernateGsonBuilderConfigurer implements GsonBuilderConfigurer {

   private final SessionFactory sessionFactory;

   private final ProxySerializer proxySerializer;

   private final EntitySerializer entitySerializer;

   public HibernateGsonBuilderConfigurer(SessionFactory sessionFactory) {
      this.sessionFactory = sessionFactory;
      this.proxySerializer = new ProxySerializer(sessionFactory);
      this.entitySerializer = new EntitySerializer(sessionFactory);
   }

   @Override
   public void config(GsonBuilder builder) {
      Map<String, ClassMetadata> allClassMetadata = this.sessionFactory.getAllClassMetadata();
      for(ClassMetadata classMetadata : allClassMetadata.values()) {
         Class mappedClass = classMetadata.getMappedClass(EntityMode.POJO);
         if (!classMetadata.isInherited()){
            builder.registerTypeHierarchyAdapter(mappedClass, this.proxySerializer);
         }
         builder.registerTypeAdapter(mappedClass, this.entitySerializer);
      }
   }
}
